package com.mooltik.sync;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.mooltik.R;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.mooltik.Utils.isEmptyOrNull;
import static com.mooltik.Utils.showToast;

public class Synchronizer {

    private static String user;
    private static String pass;
    private static SharedPreferences settings;
    private static String token;
    private static DefaultHttpClient client;
    private static final String DOCUMENT_NAME = "Notes";

    public static String sync(String data, SharedPreferences settings, final Context notesActivity) throws IOException, SAXException, ParserConfigurationException {
        Synchronizer.settings = settings;

        checkCredentials(settings, notesActivity);

        checkForUpdate();


        return null;
    }

    private static void checkForUpdate() throws IOException, ParserConfigurationException, SAXException {

        String resourceID = settings.getString("resourceId", null);

        if (resourceID == null) {


            HttpGet listRequest = new HttpGet("https://docs.google.com/feeds/default/private/full");

            listRequest.setHeader("Authorization", "GoogleLogin auth=" + token);
            listRequest.setHeader("GData-Version", "3.0");

            HttpResponse response = client.execute(listRequest);
            HttpEntity resEntity = response.getEntity();
            String body = EntityUtils.toString(resEntity);

            resourceID = getResourceID(body);

        }

        if (resourceID == null) {
            resourceID = createNotesDocument();
        }

        if (resourceID != null) {
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("resourceId", resourceID);
            editor.commit();
        }



    }

    private static String getResourceID(String body) {
        int pos;
        if ((pos = body.indexOf("<title>" + DOCUMENT_NAME + "</title>")) != -1) {
            int start = body.indexOf("<gd:resourceId>", pos) + "<gd:resourceId>".length();
            int end = body.indexOf("</gd:resourceId>", pos);
            return body.substring(start + 9, end);
        }
        return null;
    }


    private static String createNotesDocument() throws IOException {
        HttpPost post = new HttpPost("https://docs.google.com/feeds/default/private/full");
        post.setHeader("Authorization", "GoogleLogin auth=" + token);
        post.setHeader("GData-Version", "3.0");

        StringEntity stringEntity = new StringEntity("<?xml version='1.0' encoding='UTF-8'?>" +
                "<entry xmlns=\"http://www.w3.org/2005/Atom\"><category scheme=\"http://schemas.google.com/g/2005#kind\" term=\"http://schemas.google.com/docs/2007#document\"/>" +
                "<title>" + DOCUMENT_NAME + "</title></entry>");

        stringEntity.setContentType("application/atom+xml");
        post.setEntity(stringEntity);


        HttpResponse response = client.execute(post);
        String responseBody = EntityUtils.toString(response.getEntity());
        return getResourceID(responseBody);

    }

    private static Dialog checkCredentials(SharedPreferences settings, Context notesActivity) {
        pass = settings.getString("pass", null);
        user = settings.getString("user", null);

        if (isEmptyOrNull(user)) {
            user = getGoogleAccount(notesActivity);
        }

        if (isEmptyOrNull(pass)) {
            return showPasswordDialog(notesActivity);
        }

        fetchToken(notesActivity);

        return null;
    }

    private static Dialog showPasswordDialog(final Context notesActivity) {

        final Dialog dialog = new Dialog(notesActivity);
        dialog.setContentView(R.layout.userpass_dialog);
        dialog.setTitle("Google account credentials");

        final EditText userEdit = (EditText) dialog.findViewById(R.id.username);
        userEdit.setText(user);

        final EditText passEdit = (EditText) dialog.findViewById(R.id.password);

        Button okButton = (Button) dialog.findViewById(R.id.dialogOkButton);
        okButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                user = userEdit.getText().toString();
                pass = passEdit.getText().toString();

                saveCredentials();

                dialog.dismiss();

                fetchToken(notesActivity);
            }
        });

        dialog.show();
        return dialog;
    }


    private static void saveCredentials() {
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("user", user);
        editor.putString("pass", pass);
        editor.commit();
    }

    public static String getGoogleAccount(Context notesActivity) {
        AccountManager accountManager = AccountManager.get(notesActivity);
        Account[] accounts = accountManager.getAccountsByType("com.google");
        return accounts[0].name.trim();
    }

    public static void fetchToken(Context notesActivity) {
        try {

            client = new DefaultHttpClient();

            HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("accountType", "GOOGLE"));
            nvps.add(new BasicNameValuePair("Email", user));
            nvps.add(new BasicNameValuePair("Passwd", pass));
            nvps.add(new BasicNameValuePair("service", "writely"));// Name of Google service
            nvps.add(new BasicNameValuePair("source", "Notes-Notes-1.0"));
            UrlEncodedFormEntity ent;

            ent = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
            post.setEntity(ent);

            HttpResponse responsePOST = client.execute(post);
            HttpEntity resEntity = responsePOST.getEntity();

            if (resEntity != null) {
                String authToken = EntityUtils.toString(resEntity);
                token = authToken.substring(authToken.indexOf("Auth=") + 5, authToken.length()).trim();
            }


        } catch (IOException e) {
            pass = null;
            saveCredentials();
            showToast("Can't authenticate: " + e.getLocalizedMessage(), notesActivity);
        }
    }
}
